package com.lry.basic.mq;

/**
 * @author:刘仁有
 * @desc:
 * @email:953506233@qq.com
 * @data:2019/6/19
 */
public class Looper {
    private static ThreadLocal<Looper> threadLocal = new ThreadLocal<>();
    MessageQueue queue;
    public Looper(){
        queue = new MessageQueue();
    }
    public static Looper getLooper(){
        return threadLocal.get();
    }
    public static void prepare(){
        Looper lopper=getLooper();
        if(lopper!=null){
            throw new RuntimeException("only one looper may be created per thread");
        }
        threadLocal.set(new Looper());
    }

    public static void loop(){
        Looper me=getLooper();
        if(me==null){
            throw new RuntimeException("No Looper:Looper.prepare() wasn't called on this thread.");
        }
        for(;;){
            Message msg = me.queue.deque();
            if(msg!=null){
                msg.target.dispatherMessage(msg);
            }
        }

    }
}
